import { THEME_LIGHT, THEME_DARK, THEME_SYSTEM } from '@/constants'
import { watch } from 'vue'
import store from '@/store'

// 跟随系统颜色 利用window.matchMedia 方法来实现主题颜色的切换

let matchMedia
const flowSystemTheme = () => {
  if (matchMedia) return
  matchMedia = window.matchMedia('(prefers-color-scheme: dark)')
  //   监听主题变化
  matchMedia.onchange = () => {
    //   获取当前主题颜色
    changeTheme(THEME_SYSTEM)
  }
}

const changeTheme = (theme) => {
  let htmlClassName = ''
  switch (theme) {
    case THEME_LIGHT:
      htmlClassName = 'light'
      break
    case THEME_DARK:
      htmlClassName = 'dark'
      break
    case THEME_SYSTEM:
      flowSystemTheme()
      htmlClassName = matchMedia.matches ? 'dark' : 'light'
      break
  }
  document.querySelector('html').className = htmlClassName
}
// 初始化主题颜色
export default () => {
  watch(
    () => store.getters.themeType,
    (val) => changeTheme(val),
    { immediate: true }
  )
}
